import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { logColorEvent } from '@/utils/colorDebugger'

export const useGameStore = defineStore('game', () => {
  // 状态
  const currentRoom = ref(null)
  const gameStatus = ref('waiting') // waiting, playing, finished
  const players = ref([])
  const timeLeft = ref(0)
  const gameDuration = ref(180) // 3分钟
  const brushSize = ref(12) // 画笔大小
  const playerAreas = ref(new Map())
  const currentPlayer = ref(null)
  const isConnected = ref(false)
  
  // 新增：房间管理状态
  const roomInfo = ref(null)
  const chatMessages = ref([])
  const connectionStatus = ref('disconnected') // disconnected, connecting, connected, reconnecting
  const lastError = ref(null)
  const isHost = ref(false)

  // 计算属性
  const sortedPlayers = computed(() => {
    return [...players.value].sort((a, b) => {
      const areaA = playerAreas.value.get(a.id) || 0
      const areaB = playerAreas.value.get(b.id) || 0
      return areaB - areaA
    })
  })

  const winner = computed(() => {
    if (gameStatus.value !== 'finished') return null
    return sortedPlayers.value[0]
  })

  const totalArea = computed(() => {
    let total = 0
    for (const area of playerAreas.value.values()) {
      total += area
    }
    return total
  })

  const canStartGame = computed(() => {
    return isHost.value && 
           gameStatus.value === 'waiting' && 
           players.value.length >= 2 &&
           isConnected.value
  })

  const canJoinRoom = computed(() => {
    return !currentRoom.value && isConnected.value
  })

  const canLeaveRoom = computed(() => {
    return currentRoom.value !== null
  })

  const playerCount = computed(() => players.value.length)

  // 动作
  function setRoom(room) {
    currentRoom.value = room
  }

  function setGameStatus(status) {
    gameStatus.value = status
  }

  function setPlayers(playerList) {
    players.value = playerList
  }

  function addPlayer(player) {
    console.log('添加玩家:', player)
    logColorEvent('addPlayer', player)
    
    const existingPlayerIndex = players.value.findIndex(p => p.id === player.id)
    if (existingPlayerIndex === -1) {
      // 新玩家，直接添加
      players.value.push(player)
    } else {
      // 更新现有玩家的信息（特别是颜色）
      players.value[existingPlayerIndex] = { ...players.value[existingPlayerIndex], ...player }
    }
    
    // 如果是当前玩家，同步颜色信息
    if (currentPlayer.value && currentPlayer.value.id === player.id) {
      currentPlayer.value.avatarColor = player.avatarColor || player.color
      currentPlayer.value.brushColor = player.brushColor || player.color
      currentPlayer.value.color = player.brushColor || player.color // 保持向后兼容
      console.log('当前玩家颜色已更新:', {
        avatarColor: currentPlayer.value.avatarColor,
        brushColor: currentPlayer.value.brushColor
      })
      logColorEvent('currentPlayerColorUpdated', {
        playerId: currentPlayer.value.id,
        avatarColor: currentPlayer.value.avatarColor,
        brushColor: currentPlayer.value.brushColor
      })
    }
  }

  function removePlayer(playerId) {
    const index = players.value.findIndex(p => p.id === playerId)
    if (index > -1) {
      players.value.splice(index, 1)
    }
  }

  function updatePlayerArea(playerId, area) {
    // 通过替换 Map 引用触发响应式更新
    const next = new Map(playerAreas.value)
    next.set(playerId, Number(area) || 0)
    playerAreas.value = next
  }

  function setTimeLeft(time) {
    timeLeft.value = time
  }

  function setCurrentPlayer(player) {
    currentPlayer.value = player
    // 检查是否为房主
    isHost.value = currentRoom.value && currentRoom.value.hostId === player.id
  }

  function setConnectionStatus(status) {
    isConnected.value = status
    connectionStatus.value = status ? 'connected' : 'disconnected'
  }

  function setConnectionState(state) {
    connectionStatus.value = state
    isConnected.value = state === 'connected'
  }

  function setRoomInfo(info) {
    console.log('GameStore setRoomInfo 被调用:', info)
    logColorEvent('setRoomInfo', { info })
    roomInfo.value = info
    // 更新玩家列表（兼容 PascalCase 与 camelCase）
    if (info) {
              const playersPayload = info.Players || info.players || []
        const ownerIdFromServer = info.OwnerId || info.ownerId || null
        if (Array.isArray(playersPayload)) {
          players.value = playersPayload.map((p, index) => {
            const pid = p.PlayerId || p.playerId || p.id
            const nickname = p.Nickname || p.nickname
            const avatarColor = p.AvatarColor || p.avatarColor || p.Color || p.color
            const brushColor = p.BrushColor || p.brushColor || p.Color || p.color
            const joinedAt = p.JoinedAt || p.joinedAt || Date.now()
            const isOwner = ownerIdFromServer ? pid === ownerIdFromServer : index === 0
            return { 
              id: pid, 
              nickname, 
              avatarColor, 
              brushColor, 
              color: brushColor, // 保持向后兼容，使用画笔颜色
              joinedAt, 
              isOwner 
            }
          })
        }
      
      // 更新当前玩家的房主状态和颜色
      if (currentPlayer.value) {
        const isCurrentOwner = ownerIdFromServer
          ? currentPlayer.value.id === ownerIdFromServer
          : players.value[0]?.id === currentPlayer.value.id
        currentPlayer.value.isOwner = isCurrentOwner
        isHost.value = isCurrentOwner
        
        // 同步当前玩家的颜色信息
        const playerInList = players.value.find(p => p.id === currentPlayer.value.id)
        if (playerInList) {
          currentPlayer.value.avatarColor = playerInList.avatarColor
          currentPlayer.value.brushColor = playerInList.brushColor
          currentPlayer.value.color = playerInList.brushColor // 保持向后兼容
          console.log('当前玩家颜色已同步:', {
            avatarColor: currentPlayer.value.avatarColor,
            brushColor: currentPlayer.value.brushColor
          })
        }
      }
    }
    
    // 更新房间信息
    if (info) {
      // 如果有房间名称，更新当前房间信息
      const roomName = info.RoomName || info.roomName
      const roomCode = info.RoomCode || info.roomCode
      const maxPlayersFromServer = info.MaxPlayers || info.maxPlayers
      const ownerIdFromServer = info.OwnerId || info.ownerId || null
      if (roomName && roomCode) {
        currentRoom.value = {
          id: roomCode,
          name: roomName,
          maxPlayers: maxPlayersFromServer || 6, // 使用后端传递的最大玩家数，如果没有则默认为6
          hostId: ownerIdFromServer
        }
        console.log('更新后的currentRoom:', currentRoom.value)
      }

      // 同步游戏设置（确保加入者与房主一致）
      const duration = info.GameDuration ?? info.gameDuration
      const brush = info.BrushSize ?? info.brushSize
      if (typeof duration === 'number') gameDuration.value = duration
      if (typeof brush === 'number') brushSize.value = brush
    }
    
    console.log('设置后的roomInfo:', roomInfo.value)
  }

  function addChatMessage(message) {
    // 规范化消息字段，兼容不同命名（服务端 PascalCase、本地 camelCase）
    const playerId = message.PlayerId ?? message.playerId ?? message.senderId ?? 'unknown'
    const content = message.Message ?? message.message ?? message.content ?? message.text ?? ''
    const ts = message.Timestamp ?? message.timestamp ?? Date.now()

    const normalized = {
      // 标准字段（供各组件统一使用）
      PlayerId: playerId,
      Message: String(content),
      Timestamp: ts,
      // 兼容旧字段（旧组件仍可使用）
      playerId: playerId,
      content: String(content),
      timestamp: ts,
      // 列表 key
      id: Date.now() + Math.random()
    }

    chatMessages.value.push(normalized)
    
    // 限制聊天消息数量
    if (chatMessages.value.length > 100) {
      chatMessages.value.shift()
    }
  }

  function clearChat() {
    chatMessages.value = []
  }

  function setError(error) {
    lastError.value = error
    console.error('Game Store Error:', error)
  }

  function clearError() {
    lastError.value = null
  }

  function resetGame() {
    gameStatus.value = 'waiting'
    timeLeft.value = 0
    playerAreas.value.clear()
  }

  function clearRoom() {
    currentRoom.value = null
    roomInfo.value = null
    players.value = []
    chatMessages.value = []
    isHost.value = false
    resetGame()
  }

  function updatePlayerInfo(playerId, updates) {
    const player = players.value.find(p => p.id === playerId)
    if (player) {
      Object.assign(player, updates)
    }
  }

  function setHost(hostId) {
    isHost.value = currentPlayer.value && currentPlayer.value.id === hostId
  }

  function setGameDuration(duration) {
    gameDuration.value = duration
  }

  function setBrushSize(size) {
    brushSize.value = size
  }

  return {
    // 状态
    currentRoom,
    gameStatus,
    players,
    timeLeft,
    gameDuration,
    brushSize,
    playerAreas,
    currentPlayer,
    isConnected,
    roomInfo,
    chatMessages,
    connectionStatus,
    lastError,
    isHost,
    
    // 计算属性
    sortedPlayers,
    winner,
    totalArea,
    canStartGame,
    canJoinRoom,
    canLeaveRoom,
    playerCount,
    
    // 动作
    setRoom,
    setGameStatus,
    setPlayers,
    addPlayer,
    removePlayer,
    updatePlayerArea,
    setTimeLeft,
    setCurrentPlayer,
    setConnectionStatus,
    setConnectionState,
    setRoomInfo,
    addChatMessage,
    clearChat,
    setError,
    clearError,
    resetGame,
    clearRoom,
    updatePlayerInfo,
    setHost,
    setGameDuration,
    setBrushSize
  }
})
